local spr = app.activeSprite
if not spr then return app.alert("错误：没有打开的精灵文件") end

-- 强化版小写转换
local function to_snake_case(str)
  return str:gsub("%s+", "_")          -- 空格转下划线
           :gsub("([a-z])([A-Z])", "%1_%2")  -- 驼峰拆分
           :gsub("[^%a%d_]", "_")      -- 仅保留字母数字和下划线
           :gsub("_+", "_")            -- 合并连续下划线
           :lower()                    -- 强制全小写
end

-- 自动处理基础文件名
local base_name = "untitled"
if spr.filename then
  base_name = to_snake_case(app.fs.fileTitle(spr.filename))
end

local success_count = 0
local error_log = {}

for _, tag in ipairs(spr.tags) do
  local safe_tag = to_snake_case(tag.name)
  local full_path = app.fs.joinPath(
    spr.filename and app.fs.filePath(spr.filename) or app.fs.currentPath,
    base_name .. "_" .. safe_tag .. ".png"
  )

  local ok = pcall(function()
    app.command.ExportSpriteSheet{
      ui = false,
      type = SpriteSheetType.HORIZONTAL,
      textureFilename = full_path,
      tag = tag.name,
      trim = false,
      shapePadding = 0
    }
  end)
  
  if ok then
    success_count = success_count + 1
  else
    table.insert(error_log, "["..tag.name.."]")
  end
end

-- 精简结果提示
local result_msg = ""
if success_count == #spr.tags then
  result_msg = "成功导出 "..success_count.." 个标签"
elseif success_count > 0 then
  result_msg = "部分成功 ("..success_count.."/"..#spr.tags..")\n失败标签："..table.concat(error_log, " ")
else
  result_msg = "导出失败"
end

app.alert{ title="操作结果", text=result_msg, buttons={"确定"} }